import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class ServerInterceptor implements HttpInterceptor {
  constructor(public router: Router) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // request = request.clone({
    //   setHeaders: {},
    //   setParams: {}
    // });

    // const token = localStorage.getItem('token') || '';
    // if (token) {
    //   request = request.clone({ headers: request.headers.set('token', token) });
    // }

    return next.handle(request).pipe(
      tap(
        event => {
          if (event instanceof HttpResponse) {
            if (!localStorage.getItem('accessToken') || event.status === 999) {
              this.router.navigate(['/login']);
            }
            if (event.status === 200) {
              console.log(event.url + '--ok');
            }
          }
        },
        error => {
          if (error instanceof HttpErrorResponse) {
            console.log(error);
            // token过期 服务器错误等处理
          }
        }
      )
    );
  }
}
